<!--文件上传-->
<template>
  <el-upload
    v-if="uploadType == 1"
    ref="my-upload"
    v-model:file-list="fileList"
    :accept="format"
    :action="actionUrl"
    class="upload-demo"
    :class="!isShow ? 'cp' : ''"
    :data="{
      scene: '0',
      filename: file_name,
    }"
    :headers="{
      Authorization: token,
    }"
    :limit="limitNum"
    :on-exceed="handleExceed"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :on-success="handleSuccess"
    name="image"
    :multiple="true"
    :before-upload="beforeAvatarUpload"
    :disabled="isShowButton"
    :show-file-list="showFileList2"
  >
    <el-button :disabled="isShowButton" :icon="iconType" :plain="isBorder" :type="btnType" :style="customStyle" :round="isRound">
      {{ uploadTxt }}
    </el-button>
    <template #tip>
      <div v-show="isShow" class="el-upload__tip">
        {{ formatTxt }}
      </div>
    </template>
  </el-upload>
  <el-upload
    v-else-if="uploadType == 2"
    ref="my-upload"
    v-model:file-list="fileList"
    :accept="format"
    :action="actionUrl"
    class="upload-demo"
    :data="{
      folder: fileName,
      is_delete_local: delLocal,
    }"
    :headers="{
      Authorization: token,
    }"
    :limit="limitNum"
    :on-exceed="handleExceed"
    :on-remove="handleRemove"
    :on-success="handleSuccess"
    name="file"
  >
    <div class="bd"><i class="el-icon-plus" /></div>

    <template #tip>
      <div v-show="isShow" class="el-upload__tip">
        {{ formatTxt }}
      </div>
    </template>
  </el-upload>
  <!--  照片墙  -->
  <div v-else-if="uploadType == 3">
    <el-upload
      ref="my-uploadP"
      :file-list="fileList"
      :accept="format"
      :action="actionUrl"
      :before-upload="beforeAvatarUpload"
      :data="{ file_source: file_source }"
      :headers="{ Authorization: token }"
      :limit="limitNum"
      list-type="picture-card"
      :on-exceed="handleExceed"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
      name="file"
    >
      <i class="el-icon-plus" />
      <template #tip>
        <div v-show="isShow" class="el-upload__tip">
          {{ formatTxt }}
        </div>
      </template>
    </el-upload>
    <el-image-viewer v-if="dialogVisible" :z-index="9999" :on-close="closeViewer" :url-list="[dialogImageUrl]" />
  </div>
</template>

<script>
  import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
  export default {
    name: 'Upload',
    components: { ElImageViewer },
    props: {
      title: String, // 返回的赋值属性名
      fileName: {
        type: String,
        default: 'qualification',
      },
      delLocal: {
        // 是否删除本地服务器文件 1 默认 删除 0不删除
        type: Number,
        default: 1,
      },
      uploadTxt: {
        // 上传按钮文字
        type: String,
        default: '上传附件',
      },
      iconType: String, // 上传按钮图标
      btnType: {
        // 上传按钮颜色
        type: String,
        default: 'primary',
      },
      customStyle: {
        // 上传按钮的自定义属性style
        type: String,
        default: '',
      },
      isBorder: {
        // 按钮类型
        type: Boolean,
        default: false,
      },
      isRound: {
        // 是否为圆角按钮
        type: Boolean,
        default: false,
      },
      isShowButton: {
        // 是否禁用按钮
        type: Boolean,
        default: false,
      },
      isShow: {
        // 是否显示提示
        type: Boolean,
        default: true,
      },
      showFileList: {
        // 是否显示上传列表
        type: Boolean,
        default: false,
      },
      showFileList2: {
        // 是否显示上传列表
        type: Boolean,
        default: true,
      },
      disabled: {
        // 是否禁止上传
        type: Boolean,
        default: false,
      },
      uploadType: {
        // 文件上传ui类型
        type: Number,
        default: 1,
      },
      formatTxt: {
        type: String,
        default: '支持格式：.jpg,.jpeg,.png,.gif,.bmp,tif,.pdf',
      },
      format: {
        // 上传文件格式
        type: String,
        default: '.jpg,.jpeg,.png,.gif,.bmp,tif,.pdf,.JPG,.JPEG,.PNG,.GIF,.BMP,.TIF,.PDF',
      },
      limitNum: {
        // 最大允许上传个数
        type: Number,
        default: 10,
      },
      // 上传是否携带文件名
      is_file_name: { type: Boolean, default: false },
      fileArr: Array, // 默认已上传成功列表
      maxSize: { type: Number, default: 10 },
      // 上传到后台的文件夹
      file_source: {
        type: String,
        default: '',
      },
    },
    emits: ['reUpload', 'beforeUpload'],
    data() {
      return {
        // actionUrl: process.env.VUE_APP_BASE_API + '/api/upload/uploadImages',
        actionUrl: '/api/upload/uploadImages',
        token: localStorage.getItem('admin-pro-token'),
        arrList: [],
        dialogImageUrl: '',
        dialogVisible: false,
        fileList: [],
        file_name: '',
      }
    },
    watch: {
      fileArr(n) {
        this.arrList = this.fileArr?.map(function (item) {
          return item
        })
        this.fileList = this.fileArr?.map(function (item) {
          return { url: 'http://106.52.70.79:2108' + item }
        })
        console.log('this.fileList: ', this.fileList)

        //   this.$emit("reUpload", [this.title, this.arrList]);
      },
    },
    mounted() {
      // bus.$on("clearFiles", this.clearFiles);
    },
    methods: {
      // 点击下载上传成功的列表
      handlePreview(file) {
        if (file.url) {
          window.open(file.url, '_blank')
        } else {
          window.open(file?.response?.data?.file_url, '_blank')
        }
      },
      handlePictureCardPreview(file) {
        console.log('file: ', file)
        this.dialogVisible = true
        this.dialogImageUrl = file.url
      },
      // 限制文件上传个数
      handleExceed(files, fileList) {
        console.log('上传个数files: ', files)
        this.$message.warning(`请最多上传 ${this.limitNum} 个文件。`)
      },
      // 中断上传
      abort_res() {
        this.$refs.upload.abort()
      },
      // 照片墙上传文件类型  上传前的钩子函数
      beforeAvatarUpload(file) {
        console.log('file: ', file)
        this.file_name = this.is_file_name ? file.name : ''

        const fileType = file.name.substring(file.name.lastIndexOf('.'))
        const acceptTypes = this.format.split(',')

        const maxSize = file.size / 1024 / 1024 < this.maxSize
        if (!maxSize) {
          this.$message.warning(`上传文件大小不能超过 ${this.maxSize}MB!`)
          return false
        }

        if (acceptTypes.indexOf(fileType) == -1) {
          this.$message.warning(`上传文件格式不能是 ${fileType}!`)
          return false
        }
      },
      // 清空上传文件
      clearFiles() {
        // this.$refs['my-upload'].clearFiles();
        this.arrList = []
        this.fileList = []
        this.$emit('reUpload', [this.title, []])
      },
      // 删除上传文件
      handleRemove(file, fileList) {
        console.log('file: ', file)
        if (file.status == 'success') {
          // 照片墙
          if (file.response) {
            const img = '/' + file.response.data.destination.split('/')[2] + '/' + file.response.data.filename
            this.arrList.splice(this.arrList.indexOf(img), 1)
          } else {
            this.arrList.splice(this.arrList.indexOf(file.url), 1)
          }
          this.$emit('reUpload', this.arrList)
          this.$message.success(`删除成功`)
        } else {
          this.$message.error(`删除失败`)
        }
      },
      // 上传时
      handleProgress() {
        this.$emit('handleProgress')
      },
      // 上传成功
      handleSuccess(response, file, fileList) {
        console.log('response: ', response)
        if (response.code == '200') {
          // 照片墙
          if (this.uploadType == 3) {
            let img = response.data.path.replace(/\\/g, '/').split('/')
            console.log('img: ', img)
            let url = img.splice(2).join('/')
            console.log('url: ', url)
            this.arrList.push('/' + url)
          }
          this.$emit('reUpload', this.arrList)
          this.$message.success(`上传成功`)
        } else {
          this.$message.error(response.message)
        }
      },
      closeViewer() {
        this.dialogVisible = false
      },
    },
  }
</script>

<style lang="scss" scoped>
  .bd {
    padding: 5px 60px;
    border: 1px dashed #ccc;
    border-radius: 5px;
  }

  :deep(.upload-demo.cp) {
    .el-upload-list {
      //position: relative;
      //top: 20px;
      //left: -229px;
      width: 275px;
    }
  }

  .el-upload--text {
    position: relative;
    box-sizing: border-box;
    width: 360px;
    height: 180px;
    overflow: hidden;
    text-align: center;
    cursor: pointer;
    background-color: #fff;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
  }

  .el-upload--text .el-icon-upload {
    margin: 40px 0 16px;
    font-size: 67px;
    line-height: 50px;
    color: #97a8be;
  }

  .el-upload--text {
    font-size: 14px;
    color: #97a8be;
    text-align: center;
  }

  .el-upload--text em {
    font-style: normal;
  }

  .upload-demo-1 {
    width: 120px;
    height: 120px;
  }
  .upload-demo-4 {
    width: 500px;
  }
  .el-upload__tip {
    color: #409eff;
  }
</style>
